package co.chuangdian.oflauncher.widgets.system;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;

public class MusicPlayerService extends Service {

	private MediaPlayer mediaPlayer = new MediaPlayer();

	private List<Music> list;
	private MusicBinder mBinder;

	public class MusicBinder extends Binder {

		public MusicPlayerService getService() {
			return MusicPlayerService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		mBinder = new MusicBinder();
		list = MusicList.getInstance(this).getMusicList();

		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			// 播放完成监听
			@Override
			public void onCompletion(MediaPlayer mp) {
				Intent intent = new Intent();
				intent.setAction("co.chuangdian.launcher.NextMusicReceiver");
				sendBroadcast(intent);
			}
		});

		return mBinder;
	}
	public void seekTo(int progress){
		mediaPlayer.seekTo(progress);
	}
	/**
	 * 播放音乐
	 * 
	 * @param position
	 */
	public void play(String music_path) {
		try {
			mediaPlayer.reset();
			// 把各项参数恢复到初始状态
			mediaPlayer.setDataSource(music_path);
			mediaPlayer.prepare(); // 进行缓冲
			addTimer();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void play(int position) {
		String path = list.get(position).getUrl();
		play(path);
	}

	/**
	 * 暂停音乐
	 */
	public void pause() {
		if (mediaPlayer != null /** mediaPlayer.isPlaying() */
		) {
			mediaPlayer.pause();
		}
	}

	/**
	 * 停止音乐
	 */
	public void stop() {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			try {
				mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDestroy() {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			if(timer != null){
				timer.cancel();
				timer = null;
			}
		}
	}

	Timer timer;

	public void addTimer() {
		if (timer == null) {
			timer = new Timer();
			timer.schedule(new TimerTask() {

				@Override
				public void run() {
					// 获取歌曲总时长
					int duration = mediaPlayer.getDuration();
					// 获取歌曲当前播放进度
					int currentPosition = mediaPlayer.getCurrentPosition();

					Intent intent = new Intent();
					intent.putExtra("duration", duration);
					intent.putExtra("currentPosition", currentPosition);

					intent.setAction("co.chuangdian.launcher.CurrentPositionReceiver");
					sendBroadcast(intent);

				}
				// 开始计时任务后的5毫秒，第一次执行run方法，以后每500毫秒执行一次
			}, 5, 500);
		}
	}

	public boolean isMusicPlaying() {
		if (mediaPlayer != null) {
			return mediaPlayer.isPlaying();
		}
		return false;
	}

	public void replay() {
		if (mediaPlayer != null) {
			mediaPlayer.start();
		}
	}
}
